package com.gitee.elead.web.cors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import cn.hutool.core.util.StrUtil;
import lombok.Setter;
import lombok.experimental.Accessors;

@Setter
@Accessors(chain = true)
@Configuration
@ConfigurationProperties(prefix = "spring.cross")
public class CrossInterceptor implements HandlerInterceptor {

	private String accessControlAllowOrigin;

	private String accessControlAllowHeaders = "Content-Type, Authorization, x-token, sso_sessionid";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String curOrigin = request.getHeader(HttpHeaders.ORIGIN);
		if (StrUtil.isNotBlank(curOrigin)) {
			// 为空代表支持所有
			if (StrUtil.isBlank(accessControlAllowOrigin)) {
				response.addHeader("Access-Control-Allow-Origin", curOrigin);
			} else {
				String[] allowUrls = StrUtil.split(accessControlAllowOrigin, StrUtil.COMMA);
				for (String origin : allowUrls) {
					if (origin.equals(curOrigin)) {
						response.addHeader("Access-Control-Allow-Origin", origin);
					}
				}
			}
		}
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
		response.setHeader("Access-Control-Allow-Headers", accessControlAllowHeaders);
		response.setHeader("Access-Control-Max-Age", "3600");
		return true;
	}
	
	 
	//配置允许跨域的域名(yaml配置方式)
    public void setAllow(String allow){
        if(StrUtil.isNotBlank(allow)){
        	accessControlAllowOrigin = allow;
        }
    }
    
    //配置允许跨域的头(yaml配置方式)
    public void setHeader(String header){
    	if(StrUtil.isNotBlank(header)){
    		accessControlAllowHeaders = header;
    	}
    }
}